package com.fsl.springbootdesignpattern.n_prototype;

import java.io.*;
import java.util.ArrayList;

public class Student extends Prototype implements Serializable {

    private Integer age;

    private String name;

    private ArrayList<String> list = new ArrayList<>();

    //假如想实现非基本类型拷贝（深拷贝），必须要对非基本类型重新设置才行
    //但是这里还有一个问题，就是假如list里面不是简单类型，而是复杂类型，这样就没有办法实现了
    /*@Override
    protected Object clone() throws CloneNotSupportedException {
        Student student = null;
        student = (Student)super.clone();
        student.setList((ArrayList)list.clone());
        return student;
    }*/


    /**
     * 假如想实现非基本类型拷贝（深拷贝）,可以重写clone方法按照如下方式进行序列化和反序列化操作
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Student clone() throws CloneNotSupportedException {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try{
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            return (Student)ois.readObject();
        }
        catch (Exception e){

        }
        finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if(oos != null){
                    oos.close();
                }
                if(bis != null){
                    oos.close();
                }
                if(ois != null){
                    oos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return (Student)super.clone();
    }

    public ArrayList<String> getList() {
        return list;
    }

    public void setList(ArrayList<String> list) {
        this.list = list;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
